﻿using MCPSSETest.Utils;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Playwright;
using ModelContextProtocol.Server;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

namespace MCPSSETest.Tools
{
    [McpServerToolType]
    public sealed class TGTool
    {
        private async Task<string> CheckCreditReporting([Description("姓名")] string name, [Description("身份证号")] string IDNumber)
        {

            using var playwright = await Playwright.CreateAsync();

            // 启动浏览器(非无头模式)
            await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = false, // 可视化浏览器窗口
                Channel = "msedge",

            });

            // 创建新页面
            var page = await browser.NewPageAsync();
            //await page.SetExtraHTTPHeadersAsync(new Dictionary<string, string>() { { "Host", "zxgk.court.gov.cn" },{ "Pragma","no-cache" } });
            try
            {

                var shixin = await page.GotoAsync("https://zxgk.court.gov.cn/shixin/");
                var pageOk = shixin?.Ok ?? false;
                while (!pageOk)
                {
                    await page.WaitForTimeoutAsync(8000);
                    shixin = await page.ReloadAsync();
                    // 打开登录页面
                    Console.WriteLine(shixin?.StatusText);
                    pageOk = shixin?.Ok ?? false;
                }

                // 输入账号和密码
                await page.FillAsync("input[id=\"pName\"]", name);
                await page.WaitForTimeoutAsync(5000);
                await page.FillAsync("input[id=\"pCardNum\"]", IDNumber);



                Console.WriteLine("enddd");
                await page.WaitForTimeoutAsync(500000);

                return "";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                await page.CloseAsync();
            }

            return "";
        }

        [McpServerTool]
        public async Task<string> WebScraperScreenshotAsync([Description("页面url")] string url= "https://admin.tgmohe.com/form/_fcmhp9uvjm5/layout/__default/list")
        {
            using var playwright = await Playwright.CreateAsync();

            // 启动浏览器(非无头模式)
            await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = false, // 可视化浏览器窗口
                //Channel = "msedge",
            });
            // 创建新页面
            var page = await browser.NewPageAsync(new BrowserNewPageOptions() {
                //ExtraHTTPHeaders = new KeyValuePair<string, string>[]
                //{
                //    new("authorization", "Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjNhMTg4ZmFkLTJhOWMtYzA1MS1kMTYwLTU5OTRjNzc3NmYyYiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiLmnY7luIUiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9naXZlbm5hbWUiOiLmnY7luIUiLCJ0ZW5hbnRpZCI6IjNhMDk1YTk1LTY4ZmUtYzZiNi0wZGMwLTYyNTYwNjhlMjgyOSIsImRlcHRfaWQiOiIwYWRlZGJlNy04NTdjLTQ2MDUtOTRiMi04ZjgwZGIzMmYxZmUiLCJleHAiOjE3NTg4Njg0ODgsImlzcyI6InQtYnVpbGQiLCJhdWQiOiJ0LWJ1aWxkIn0.zyywch-nVNCE5pfMcI2-wbcCcwzd5k90NF81W3SAV67ungIloNbEUASuwmfmqT-QsBWCd4v1fa2fZMQgwTbQFA")
                //}
            });
            var openMenuTimeList = new JArray();
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            try
            {
                // 打开登录页面
                await page.GotoAsync("https://admin.tgmohe.com");
                await page.WaitForTimeoutAsync(2000);
               
                await page.EvaluateAsync("localStorage.setItem('PAGE_TIMER', 1); ");
                // 输入账号和密码
                await page.FillAsync("input[id=\"form_item_phoneNumber\"]", "16638640391");
                await page.WaitForTimeoutAsync(500);
                await page.FillAsync("input[id=\"form_item_password\"]", "xxxx");

                // 点击登录按钮
                await page.GetByRole(AriaRole.Button, new PageGetByRoleOptions { Name = "登 录" }).ClickAsync();
                await page.GetByTitle("尚谦亿集团").ClickAsync();

                //单独页面测试
                {

                    //stopwatch.Restart();
                    //var shixin = await page.GotoAsync(url);
                    //// 方式3：等待页面完全稳定（包括动态内容）
                    //await page.WaitForLoadStateAsync(LoadState.NetworkIdle);
                    //stopwatch.Stop();
                    //Console.WriteLine($"NetworkIdle  执行时间: {stopwatch.ElapsedMilliseconds} ms");

                    //return "";

                }

                //读取
                var list = ExcelHelper.GetExcelJArray("C:\\Users\\23635\\Desktop\\menu_list.xlsx");
                list = new JArray(list.Where(l => l.SelectToken("企业名称")?.ToString() == "尚谦亿集团"));
                foreach (var item in list)
                {
                    //Console.WriteLine(JsonConvert.SerializeObject(item));
                    var path = GetUrlByMenu(item);
                    if (string.IsNullOrEmpty(path))
                        continue;


                    stopwatch.Restart();
                    await page.GotoAsync(path);
                    var pageTime = string.Empty;

                    // 方式1：等待特定元素出现（推荐）
                    //await page.WaitForSelectorAsync("css选择器", new PageWaitForSelectorOptions
                    //{
                    //    State = WaitForSelectorState.Visible,
                    //    Timeout = 10000 // 10秒超时
                    //});
                    //await page.WaitForTimeoutAsync(6000);



                    //await page.WaitForLoadStateAsync(LoadState.Load);
                    //await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
                    // 方式3：等待页面完全稳定（包括动态内容）
                    await page.WaitForLoadStateAsync(LoadState.NetworkIdle);
                    try
                    {
                        pageTime = await page.GetByTitle("本次页面加载耗时").InnerTextAsync();
                        Console.WriteLine($"{item.SelectToken("菜单名称")} 加载耗时:{pageTime}");
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("加载失败");
                    }

                    stopwatch.Stop();
                    Console.WriteLine($"{item.SelectToken("菜单名称")}  playwright: {stopwatch.ElapsedMilliseconds} ms");

                    openMenuTimeList.Add(new JObject
                    {
                        ["菜单名"] = item.SelectToken("菜单名称")?.ToString(),
                        ["dom渲染时间"] = pageTime,
                        ["页面网络加载时间"] = stopwatch.ElapsedMilliseconds
                    });
                }

                // 获取Base64格式的截图
                //var screenshotBytes = await page.ScreenshotAsync(new PageScreenshotOptions
                //{
                //    Type = ScreenshotType.Png, // 指定为PNG格式
                //    FullPage = true // 可选：截取整个页面
                //});
                //return QiNiuHelper.UploadData(screenshotBytes);

            }
            catch(Exception e)
            {
                Console.WriteLine($"error:{e.Message}");

            }
            finally
            {
                // 方法1：写入新文件
                string filePath = "output.xlsx";
                ExcelHelper.WriteJArrayToExcel(openMenuTimeList, filePath, "菜单打开时间");
                Console.WriteLine("数据已写入Excel文件");
            }
            return default;
        }

        [McpServerTool]
        public async Task<string> WebScraper([Description("尚谦亿账号")]string userName, [Description("尚谦亿密码")] string password)
        {
            using var playwright = await Playwright.CreateAsync();

            // 启动浏览器(非无头模式)
            await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = false, // 可视化浏览器窗口
                //Channel = "msedge",
            });
            // 创建新页面
            var page = await browser.NewPageAsync(new BrowserNewPageOptions()
            {
                //ExtraHTTPHeaders = new KeyValuePair<string, string>[]
                //{
                //    new("authorization", "Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjNhMTg4ZmFkLTJhOWMtYzA1MS1kMTYwLTU5OTRjNzc3NmYyYiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiLmnY7luIUiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9naXZlbm5hbWUiOiLmnY7luIUiLCJ0ZW5hbnRpZCI6IjNhMDk1YTk1LTY4ZmUtYzZiNi0wZGMwLTYyNTYwNjhlMjgyOSIsImRlcHRfaWQiOiIwYWRlZGJlNy04NTdjLTQ2MDUtOTRiMi04ZjgwZGIzMmYxZmUiLCJleHAiOjE3NTg4Njg0ODgsImlzcyI6InQtYnVpbGQiLCJhdWQiOiJ0LWJ1aWxkIn0.zyywch-nVNCE5pfMcI2-wbcCcwzd5k90NF81W3SAV67ungIloNbEUASuwmfmqT-QsBWCd4v1fa2fZMQgwTbQFA")
                //}
            });
            var openMenuTimeList = new JArray();
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            try
            {
                // 打开登录页面
                await page.GotoAsync("https://admin.tgmohe.com");
                await page.WaitForTimeoutAsync(1000);

                await page.EvaluateAsync("localStorage.setItem('PAGE_TIMER', 1); ");
                // 输入账号和密码
                await page.FillAsync("input[id=\"form_item_phoneNumber\"]", userName);
                await page.WaitForTimeoutAsync(500);
                await page.FillAsync("input[id=\"form_item_password\"]", password);

                // 点击登录按钮
                await page.GetByRole(AriaRole.Button, new PageGetByRoleOptions { Name = "登 录" }).ClickAsync();
                await page.GetByTitle("尚谦亿集团").ClickAsync();

                // 方式3：等待页面完全稳定（包括动态内容）
                await page.WaitForLoadStateAsync(LoadState.NetworkIdle);
                await Task.Delay(5000);
                {
                    //测试
                    //stopwatch.Restart();
                    //await page.GotoAsync("https://admin.tgmohe.com/form/report-forms/table/3a104c98-725f-71e8-1deb-29b2dde2a652");
                    //await page.WaitForLoadStateAsync(LoadState.NetworkIdle);
                    //while((await page.Locator("div.ant-spin-dot").AllAsync()).Any())
                    //{
                    //    var s = (await page.Locator("div.ant-spin-dot").AllAsync()).Any();
                    //    await Task.Delay(100);
                    //}
                    //stopwatch.Stop();
                    //Console.WriteLine($"time: {stopwatch.Elapsed}");
                    //return "";

                }

                var sideList = await page.Locator("div.side-item > div").AllAsync();
                var allowClickMenuList = sideList.Take(sideList.Count - 1).ToList();
                var sideMapMenuList = await page.Locator("ul[role]").AllAsync();
                foreach (var item in allowClickMenuList.Select((s,i)=>(s,i)))
                {
                    await item.s.ClickAsync();
                    //防止浏览器太慢导致二级菜单无法点击
                    await Task.Delay(1000);

                    var sideMapMenu = sideMapMenuList.Skip(item.i).First();

                    var secondMenuList = await sideMapMenu.Locator("li.ant-menu-submenu.ant-menu-submenu-inline.side-sub-menu").AllAsync();
                    foreach (var smenu in secondMenuList)
                    {
                        var secondGroupName = await smenu.Locator("div.ant-menu-submenu-title").InnerTextAsync();
                        Console.WriteLine($"二级菜单组名为：{secondGroupName}");

                        //if (secondGroupName != "数据分析")
                        //{
                        //    continue;
                        //}

                        //防止具体菜单组加载太慢，无法点击具体菜单
                        await Task.Delay(1000);
                        await smenu.ClickAsync();
                        //防止具体菜单组加载太慢，无法点击具体菜单
                        await Task.Delay(1000);
                        var smenus = await smenu.Locator("ul> li").AllAsync();
                        foreach (var sm in smenus)
                        {
                            //sm才可以点
                            var menuName = await sm.Locator("span.text-wrapper").InnerTextAsync();
                            if(menuName == "我的薪资")
                            {
                                //处理弹框导致无法继续模拟
                                continue;
                            }

                            //if (menuName != "工程登记表")
                            //{
                            //    continue;
                            //}

                            var pageTime = string.Empty;
                            await sm.ClickAsync();

                            // 方式3：等待页面完全稳定（包括动态内容），不可靠   科目汇总表  资源占用   工程登记表  三栏式总账  实时报表数据
                            await page.WaitForLoadStateAsync(LoadState.NetworkIdle);
                            //放在前面，防止未发起请求，while等待失效
                            await Task.Delay(5000);
                            //防止拿到菜单页面未加载完的加载时间
                            var whileCount = 0;
                            stopwatch.Restart();
                            while ((await page.Locator("div.ant-spin-dot").AllAsync()).Any())//超过10s前端就不统计了
                            {
                                whileCount++;
                                await Task.Delay(2000);
                            }
                            stopwatch.Stop();
                            //等待vue修改界面展示值
                            await Task.Delay(1500);

                            var menuType = GetMenuTypeByUrl(page.Url);
                            try
                            {
                                if (whileCount >= 3)
                                {
                                    pageTime = $"{stopwatch.Elapsed.TotalSeconds:F1} ";
                                }
                                else if (!page.Url.Contains("admin.tgmohe.com"))
                                {
                                    pageTime = "0";
                                }
                                else
                                {
                                    pageTime = await page.GetByTitle("本次页面加载耗时").Last.InnerTextAsync();//在线文档不准
                                }
                                Console.WriteLine($"{menuType} {menuName} 加载耗时:{pageTime}");
                            }
                            catch (Exception)
                            {
                                Console.WriteLine($"{menuType} {menuName} 加载失败");
                            }


                            openMenuTimeList.Add(new JObject
                            {
                                ["菜单名"] = menuName,
                                ["dom渲染时间"] = pageTime,
                                ["类型"] = menuType
                            });
                        }

                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"error:{e.Message}");

            }
            finally
            {
                // 方法1：写入新文件
                string filePath = $"output{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                ExcelHelper.WriteJArrayToExcel(openMenuTimeList, filePath, "菜单打开时间");
                Console.WriteLine("数据已写入Excel文件");
            }
            return default;
        }

        private string GetMenuTypeByUrl(string url)
        {
            var menuType = string.Empty;
            string pattern = @"^https://admin.tgmohe.com/form/(?<formId>[^/]+)/layout/(?<layoutName>[^/]+)/(?<action>[^/]+)$";
            Match match = Regex.Match(url, pattern);
            if (match.Success)
            {
                menuType = "自定义菜单";
            }else if (url.Contains("/form/report-forms/"))
            {
                menuType = "自定义报表";
            }
            else
            {
                menuType = "预设菜单";
            }


                return menuType;
        }
        private string GetUrlByMenu(JToken obj)
        {
            var menuType = obj.SelectToken("菜单类型")?.ToString();

            if (menuType == "Form")
            {
                return $"https://admin.tgmohe.com/form/{obj.SelectToken("表单编码")?.ToString()}/layout/{obj.SelectToken("表单布局编码")}/list";
            }else if(menuType == "Link")
            {
                var url = obj.SelectToken("链接菜单地址")?.ToString()??"";
                if (url.StartsWith("http")){
                    return url;
                }
                return $"https://admin.tgmohe.com{url}";
            }else if(menuType == "Report")
            {
                var reportId = obj.SelectToken("报表id")?.ToString() ?? "";
                var reportType = obj.SelectToken("报表类型")?.ToString() ?? "";
                if(reportType == "0")
                {
                    return $"https://admin.tgmohe.com/form/report-forms/table/{reportId}";
                }
                else if (reportType == "1")
                {
                    return $"https://admin.tgmohe.com/form/report-forms/chart/{reportId}";
                }
                else if (reportType == "2")
                {
                    return $"https://admin.tgmohe.com/form/report-forms/statistical-table/{reportId}";
                }
                else if(reportType == "3")
                {
                    return $"https://admin.tgmohe.com/form/report-forms/multi-table/{reportId}";
                }
            }
            return string.Empty;
        }
    }
}
